import { Select, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { debounce, uniqBy } from 'lodash';
import { searchEmployee, searchEmployeeType1, getEmployeeInfo } from './service';

const { Option } = Select;
const ContactsInput = ({ onChange, value, onSearch, onSelect, ...options }) => {
    const [nameList, setNameList] = useState([]);
    const { applyType } = options;
    const [loading, setLoading] = useState(false);

    // 选择
    const handleSelect = sValue => {
        if (onSelect) {
            const uInfo = nameList.find(element => element.employeeCode === sValue);
            onSelect(uInfo);
        }
    };

    // 搜索员工姓名
    const handleSearch = debounce(async name => {
        // applyType 为主管发起离职 需要传departmentId，其他置空
        const params = {
            name
        };
        setLoading(true);
        const { code, data } = await (applyType && !value ? searchEmployeeType1(params) : searchEmployee(params));
        if (code === 10000) {
            const c = uniqBy(data, 'employeeCode').map(v => ({
                ...v,
                label: v.employeeName,
                value: v.employeeCode
            }));
            setNameList(c);
            setLoading(false);
        } else {
            setLoading(false);
        }
    }, 500);

    const handleChange = changeValue => {
        onChange(changeValue);
    };

    useEffect(() => {
        const fetchEmployeeInfo = async () => {
            setLoading(true);
            const { code, data } = await getEmployeeInfo(Array.isArray(value) ? value[0]?.key : value);
            if (code === 10000) {
                // 回填的时候将employeeName去搜索员工姓名
                setNameList(data.map(item => ({ ...item, label: item.employeeName, value: item.employeeCode })));
            }
            setLoading(false);
        };
        if (value) {
            fetchEmployeeInfo();
        }
    }, []);

    useEffect(() => {
        if (value && nameList.length > 0) {
            handleSelect(value);
        }
    }, [value, nameList]);

    return (
        <Spin spinning={loading}>
            <Select
                showSearch
                defaultActiveFirstOption={false}
                showArrow={false}
                filterOption={false}
                value={Array.isArray(value) ? value[0]?.key : value}
                onSearch={handleSearch}
                onChange={handleChange}
                onSelect={handleSelect}
                loading={loading}
                notFoundContent={null}
                {...options}
            >
                {nameList.map(d => (
                    <Option key={d.value}>{d.label}</Option>
                ))}
            </Select>
        </Spin>
    );
};
export default ContactsInput;
